// pages/member/myRelationship/myRelationship.js
let setTitleHandle = null; //* 定时设置页面标题handle
var app = getApp();
Page({
  /**
   * 页面的初始数据
   */
  data: {
    imgPath: app.globalData.imgPath,
    name: "",
    agent: {},
    language: "",
    activeName: "first",
    activeNameidx: 0,
    first_content: [],
    second_content: [],
    third_content: [],
    //我的推荐人
    myReferral: "",
    title1: "",
    title2: "",
    // title3: "",
    WeChat: "",
    phone: "",
    //我推荐的人
    total: 0,
    level1: "",
    level2: "",
    // level3: "",
    currentTabIndex: 0,
    is_first_content: false,
    is_second_content: false,
    is_third_content: false,
    relationLevel: "",
    keyword: "",
    level: "",
    last_page: "",
    isShowClient: false,
    // 推荐人微信、手机号是否显示
    is_recommend_wechat: 0,
    keyword1: "",
    keyword2: "",
    // keyword3: "",
    new_content: [],
    //加载更多
    isLoadMore: true,
    total_page: 0,
    page: 1,
    my_achievement: false,
    isLink: false,
    show_parents:0,
    member_order_status: "",
    dividend_id: "",
    team_dividend_levels: [] //经销商等级
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.pageInit();
    this._getMyRelation();
  },
  pageInit() {
    this.setData({
      first_content: [],
      second_content: [],
      keyword1: "",
      keyword2: "",
    });
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    let language = wx.getStorageSync("langIndex");
    this.setData({ language: language.en });
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    let that = this;
    wx.getStorage({
      key: "yz_basic_info",
      success: function (res) {
        if (setTitleHandle !== null) {
          clearTimeout(setTitleHandle);
        }
        setTitleHandle = setTimeout(function () {
          that.setData({
            agent: res.data.lang.agent ? res.data.lang.agent : {},
            name:
              res.data.lang.agent && res.data.lang.agent.agent
                ? res.data.lang.agent.agent
                : "客户",
          });
          wx.setNavigationBarTitle({
            title: that.data.name,
          });
        }, 2000);
      },
    });
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {
    clearTimeout(setTitleHandle);
  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {},

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {},

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    if (this.data.isLoadMore) {
      this.getMoreData();
    } else {
      console.log("没有更多数据");
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {},
  //我的推荐人
  _getMyRelation() {
    let that = this;
    let urlStr = app.getNetAddresss("plugin.region-external-reward.frontend.controllers.client.client.getMemberList");
    app._getNetWork({
      url: urlStr,
      data: {
        relationLevel: 1
      },
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            my_achievement: res.data.my_achievement,
            myReferral: res.data.my_referral,
            is_recommend_wechat: res.data.my_referral.is_recommend_wechat,
            self_info: res.data.my_referral.self
              ? res.data.my_referral.self
              : {},
            title1: res.data.my_referral.name1,
            title2: res.data.my_referral.name2,
            // title3: res.data.my_referral.name3,
            WeChat: parseInt(res.data.my_referral.wechat),
            phone: parseInt(res.data.my_referral.phone),
            realname: parseInt(res.data.my_referral.realname),
            isLoadMore: true,
            total_page: 0,
            page: 1,
            new_content: [],
            isShowClient: res.data.my_referral.is_show == "1" ? true : false,
            my_referral_parents: res.data.my_referral_parents,
            isLink: res.data.hasOwnProperty("is_link")
              ? res.data.is_link
              : false,
            member_order_status: res.data?.set?.member_order_status ?? 1,
            team_dividend_levels: res.data?.team_dividend_levels ?? []
          });
          that._getMyAgentBaseInfo(res.data.my_agent);
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //我推荐的人基本信息
  _getMyAgentBaseInfo(data) {
    let that = this;
    that.setData({
      total: data.total,
      level1: data.level1,
      level2: data.level2,
      // level3: data.level3,
    });
    if (!app._isTextEmpty(that.data.level1) && that.data.level1.is_show) {
      that.setData({
        activeName: "first",
        activeNameidx: 0,
        currentTabIndex: "0",
      });
      that._setDataByTabIndex(); //获取数据
      return;
    }

    if (!app._isTextEmpty(that.data.level2) && that.data.level2.is_show) {
      that.setData({
        activeName: "second",
        activeNameidx: 1,
        currentTabIndex: "1",
      });
      that._setDataByTabIndex(); //获取数据
      return;
    }
  },
  //设置选择后的数据
  _setDataByTabIndex() {
    if (this.data.currentTabIndex == "0" && !this.data.is_first_content) {
      this.setData({
        is_first_content: true,
        relationLevel: "1",
      });
      this._getData();
    } else if (
      this.data.currentTabIndex == "1" &&
      !this.data.is_second_content
    ) {
      this.setData({
        is_second_content: true,
        relationLevel: "0",
      });
      this._getData();
    } 
  },
  goMarket(evt) {
    if (!this.data.my_achievement) return;
    let marketid = evt.currentTarget.dataset.marketid;
    wx.navigateTo({
      url: "/packageD/member/myMarket/myMarket?marketid=" + marketid,
    });
  },
  gotoCustomerList(evt) {
    console.log(evt,evt.currentTarget.dataset.id,11);
    if( this.data.activeName == "first") { 
      wx.navigateTo({
        url: `/mircoApp/customerStatistics/list/list?id=${evt.currentTarget.dataset.id}&type=1`
      });
    }else {
      wx.navigateTo({
        url: "/mircoApp/customerStatistics/list/list?id=" + evt.currentTarget.dataset.id
      });
    }
  },
  gotoCustomerOrder(evt) {
    console.log(evt,evt.currentTarget.dataset.id,22);
    wx.navigateTo({
      url: "/mircoApp/customerStatistics/order/order?id=" + evt.currentTarget.dataset.id,
    });
  },
  searchbtn(e) {
    let val = e.detail.value;
    switch (this.data.currentTabIndex) {
    case "0":
      this.setData({
        keyword1: val,
      });
      break;
    case "1":
      this.setData({
        keyword2: val,
      });
      break;
    default:
      break;
    }
  },
  search() {
    let that = this;
    var page = 1;
    let keyword = "";
    this.setData({
      isLoadMore: true,
      page: 1,
      total_page: 0,
    });
    switch (this.data.currentTabIndex) {
    case "0":
      that.setData({
        relationLevel: "1",
      });
      page = 1;
      keyword = that.data.keyword1;
      break;
    case "1":
      that.setData({
        relationLevel: "0",
      });
      page = 1;
      keyword = that.data.keyword2;
      break;
    default:
      break;
    }
    let urlStr = app.getNetAddresss("plugin.region-external-reward.frontend.controllers.client.client.getMyAgentData_v2");
    urlStr += "&relationLevel=" + that.data.relationLevel;
    urlStr += "&page=" + page;
    urlStr += "&keyword=" + keyword;
    urlStr += "&level=" + that.data.level;
    urlStr += "&current_page=" + page;
    urlStr += "&last_page=" + that.data.last_page;
    urlStr += "&dividend_id=" + (that.data.relationLevel*1 ? "" : that.data.dividend_id);
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            new_content: res.data.data,
            total_page: res.data.last_page,
            page: 1,
          });
          switch (that.data.currentTabIndex) {
          case "0":
            that.setData({
              "level1.total": res.data.total,
            });
            break;
          case "1":
            that.setData({
              "level2.total": res.data.total,
            });
            break;
          default:
            break;
          }
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  // 加载更多
  getMoreData() {
    const that = this;
    var page = 1;
    let keyword = "";
    switch (this.data.currentTabIndex) {
    case "0":
      that.setData({
        relationLevel: "1",
      });
      page = 1;
      keyword = that.data.keyword1;
      break;
    case "1":
      that.setData({
        relationLevel: "0",
      });
      page = 1;
      keyword = that.data.keyword2;
      break;
    default:
      break;
    }
    that.data.isLoadMore = false; // 防止多次请求分页数据
    if (this.data.page >= this.data.total_page) {
      return;
    } else {
      this.data.page = this.data.page + 1;
      let urlStr = app.getNetAddresss("plugin.region-external-reward.frontend.controllers.client.client.getMyAgentData_v2");
      urlStr += "&relationLevel=" + that.data.relationLevel;
      urlStr += "&page=" + that.data.page;
      urlStr += "&keyword=" + keyword;
      urlStr += "&level=" + that.data.level;
      urlStr += "&current_page=" + that.data.page;
      urlStr += "&last_page=" + that.data.last_page;
      urlStr += "&dividend_id=" +  (that.data.relationLevel * 1 ? "" : that.data.dividend_id);
      app._getNetWork({
        url: urlStr,
        success: function (resdata) {
          var res = resdata.data;
          if (res.result == 1) {
            that.setData({
              new_content: that.data.new_content.concat(res.data.data),
              isLoadMore: true,
            });
          } else {
            that.setData({
              page: that.data.page - 1,
              isLoadMore: false,
            });
          }
        },
        fail: function (res) {
          console.log(res);
        },
      });
    }
  },
  //加载数据
  _getData() {
    var that = this;
    var page = 1;
    switch (this.data.currentTabIndex) {
    case "0":
      that.setData({
        relationLevel: "1",
      });
      break;
    case "1":
      that.setData({
        relationLevel: "0",
      });
      break;
    default:
      break;
    }
    let urlStr = app.getNetAddresss("plugin.region-external-reward.frontend.controllers.client.client.getMyAgentData_v2");
    urlStr += "&relationLevel=" + that.data.relationLevel;
    urlStr += "&page=" + page;
    urlStr += "&keyword=" + that.data.keyword;
    urlStr += "&level=" + that.data.level;
    urlStr += "&current_page=" + page;
    urlStr += "&last_page=" + that.data.last_page;
    urlStr += "&dividend_id=" + (that.data.relationLevel * 1 ? "" : that.data.dividend_id);
    app._getNetWork({
      url: urlStr,
      success: function (resdata) {
        var res = resdata.data;
        if (res.result == 1) {
          that.setData({
            new_content: res.data.data,
            page: 1,
            total_page: res.data.last_page,
          });
        }
      },
      fail: function (res) {
        console.log(res);
      },
    });
  },
  //tab 点击
  handleClick(e) {
    let idx = e.detail.index;
    if (idx == 0) {
      this.setData({
        activeName: "first",
        activeNameidx: 0,
      });
    } else if (idx == 1) {
      this.setData({
        activeName: "second",
        activeNameidx: 1,
        dividend_id : this.data.team_dividend_levels.length ? this.data.team_dividend_levels[0].id : ""
      });
    } 
    let name = this.data.activeName;
    let index = "";
    switch (name) {
    case "first":
      index = "0";
      break;
    case "second":
      index = "1";
      break;

    default:
      break;
    }
    if (this.data.currentTabIndex == index) {
      return;
    } else {
      this.setData({
        currentTabIndex: index,
      });
    }
    this.search();
  },
  //将微信号添加到剪贴板
  handleToggle(e) {
    let item = e.currentTarget.dataset.item;
    wx.setClipboardData({
      data: item.wechat.toString(),
      success(res) {
        wx.getClipboardData({
          success(res) {
            wx.showToast({
              icon: "none",
              title:
                "已成功将" +
                item.nickname +
                "的微信号添加到剪贴板，通过微信添加朋友可加客户好友!",
              duration: 1500,
            });
          },
        });
      },
    });
  },
  //拨打客户电话
  mobilebtn(e) {
    let mobile = e.currentTarget.dataset.mobile;
    wx.makePhoneCall({
      phoneNumber: mobile,
    });
  },
  viewAmount({ currentTarget: { dataset } }) {
    if (!this.data.isLink) {
      return;
    }
    let url = "/packageD/member/myRelationship/amount/amount";
    if (dataset.total) {
      url += "?type=total";
    }
    wx.navigateTo({
      url,
    });
  },
  viewMemberOverride(event) {
    if (!this.data.isLink) {
      return;
    }
    const id = event.currentTarget.dataset.id;
    wx.navigateTo({
      url: "/packageD/member/myRelationship/detail/detail?member_id=" + id,
    });
  },
  changeSuperior(){
    this.setData({
      show_parents: this.data.show_parents == 1?0:1
    });
  },
  tabSearch(event) {
    this.setData({
      dividend_id: event.detail.name
    })
    this.search();
  }
});
